package org.falak.receivers;

import org.falak.logic.FindPhoneNosInfo;
import org.falak.ui.ShowInfo;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.util.Log;

public class IncomingCallReceiver extends BroadcastReceiver {

	private FindPhoneNosInfo logic = null;
	private ShowInfo info = null;
	private Context context;

	@Override
	public void onReceive(Context contextGot, Intent intent) {
		Bundle bundle = intent.getExtras();
		this.context = contextGot;

		if (null == bundle)
			return;

		Log.i("IncomingCallReceiver", bundle.toString());

		String state = bundle.getString(TelephonyManager.EXTRA_STATE);

		Log.i("IncomingCallReceiver", "State: " + state);

		if (state.equalsIgnoreCase(TelephonyManager.EXTRA_STATE_RINGING)) {
			String phonenumber = bundle
					.getString(TelephonyManager.EXTRA_INCOMING_NUMBER);

			Log.i("IncomingCallReceiver", "Incomng Number: " + phonenumber);

			// Check if its a unknown number in which case it should be null or
			// no numbers. This is to prevent crashes.
			if (phonenumber != null) {
				// Skip for small numbers
				if (phonenumber.length() > 4) {
					String info = getLocation(phonenumber);
					this.getInfo().showInfo(context, info);
					// this.getInfo().showInfo(context, info);
				}
			}
		}
	}

	private String getLocation(String phoneNumber) {
		String info = null;
		if (this.getLogic().isIndian(phoneNumber)) {
			info = this.getLogic().getIndianInfo(phoneNumber);
		} else {
			info = this.getLogic().getIntlInfo(phoneNumber);
		}
		return info;
	}

	public FindPhoneNosInfo getLogic() {
		if (logic == null) {
			logic = new FindPhoneNosInfo(this.context);
		}
		return logic;
	}

	public ShowInfo getInfo() {
		if (info == null) {
			info = new ShowInfo();
		}
		return info;
	}
}
